<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/**
 * 线上大赛模型
 * Class ArticleModel
 * @package app\common\model
 */
class ContestActivity extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'contest_activity';

    /**
     * 关联新闻类型
     */
    public function conType()
    {
        return $this->hasOne(ContestActivityType::class, 'id', 'type_id');
    }

    /**
     * 用户活动报名填写信息
     */
    public static function getContestActivityApplyParam()
    {
        return [
            ['id' => 1, 'field' => 'username', 'value' => '姓名'],
            ['id' => 2, 'field' => 'id_card', 'value' => '身份证'],
            ['id' => 7, 'field' => 'adviser', 'value' => '指导老师'], //性别  
            ['id' => 8, 'field' => 'adviser_tel', 'value' => '指导老师联系方式'], //年龄  
            ['id' => 3, 'field' => 'tel', 'value' => '电话号码'],
            ['id' => 4, 'field' => 'reader_id', 'value' => '读者证'],
            ['id' => 6, 'field' => 'unit', 'value' => '单位名称'], //单位名称  
            ['id' => 5, 'field' => 'wechat_number', 'value' => '微信号'], //备注  最多100字
            // ['id' => 10, 'field' => 'accessory', 'value' => '附件'], //压缩包  最大3M  
        ];
    }
    /**
     * 检查活动报名填报信息
     * @param array $act_info 活动信息
     * @param array $real_info
     * @param $data 需要验证的真实信息id用|连接起来     1、姓名   2 、身份证号码  3、电话号码   4、读者证号    5、微信号 6、单位名称 7、指导老师  8、指导老师联系方式
     * @return array
     */
    public function checkApplyParam(array $real_info, array $data)
    {
        foreach ($real_info as $key => $val) {
            if ($val == 1) {
                if (empty($data['username']) || mb_strlen($data['username']) < 2) {
                    throw new Exception('用户名规则不正确');
                }
            } elseif ($val == 2) {
                if (empty($data['id_card']) || !is_legal_no($data['id_card'])) {
                    throw new Exception('身份证号码规则不正确');
                }
            } elseif ($val == 3) {
                if (empty($data['tel']) || !verify_tel($data['tel'])) {
                    throw new Exception('电话号码规则不正确');
                }
            } elseif ($val == 4) {
                if (empty($data['reader_id'])) {
                    throw new Exception('读者证不能为空');
                }
            } elseif ($val == 5) {
                if (empty($data['wechat_number'])) {
                    throw new Exception('微信号码不能为空');
                }
            } elseif ($val == 6) {
                if (empty($data['unit'])) {
                    throw new Exception('单位不能为空');
                }
            } elseif ($val == 7) {
                if (empty($data['adviser'])) {
                    throw new Exception('指导老师不能为空');
                }
            } elseif ($val == 8) {
                if (empty($data['adviser']) || !verify_tel($data['tel'])) {
                    throw new Exception('指导老师联系方式不正确');
                }
            }
        }
        return true;
    }

    /**
     * 获取总浏览量
     * @param con_id 大赛id
     */
    public function getBrowseNumber($con_id)
    {
        return $this->where(function ($query) use ($con_id) {
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
        })->where('is_del', 1)
            ->sum('browse_num');
    }


    /**
     * 更新浏览量
     *
     * @param con_id 大赛id  
     * @param number 多少次更新一次
     * @param second 大于秒更新一次（取决于后一次请求事件）
     */
    public function updateBrowseNumber($con_id, $number = 100, $second = 300)
    {
        if ($number == 1) {
            return $this->where('id', $con_id)->increment('browse_num', 1);
        }

        $key = $con_id . 'contest_activity_browse_number';
        $res = Cache::pull($key); //从缓存中获取缓存项然后删除，使用 pull 方法，如果缓存项不存在的话返回 null
        $data = [];
        if (empty($res)) {
            $data['number'] = 1;
            $data['create_time'] = time();
            Cache::put($key, $data, 3600 * 24);
        } else {
            //数据大于50或者时间超过5分钟，则更新一次数据
            if ($res['number'] >= $number || time() - $res['create_time'] >= $second) {
                return $this->where('id', $con_id)->increment('browse_num', $res['number'] + 1);
            } else {
                $data['number'] = $res['number'] + 1;
                $data['create_time'] = $res['create_time'];
                Cache::put($key, $data, 3600 * 24);
            }
        }
        return true;
    }


    /**
     * 列表
     * @param limit int 分页大小
     * @param node int 0 全部 活动类型    1 独立活动  2 多馆联合   
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 比赛开始时间(开始)
     * @param end_time datetime 比赛结束时间(开始)
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     * @param is_play 是否发布 0全部  1 发布  2未发布
     */
    public function lists($node = null, $keywords = null, $start_time = null, $end_time = null,$create_start_time = null, $create_end_time = null, $is_play = 1, $limit = 10)
    {
        //$manage_lib_ids = request()->manage_lib_ids;

        $res = $this->select(
            'id',
            'node',
            'title',
            'app_img as img',
            'host_handle',
            'tel',
            'con_start_time',
            'con_end_time',
            'vote_start_time',
            'vote_end_time',
            'is_reader',
            'vote_way',
            'number'/* ,'originals','promise' */,
            'intro',
            'rule_content',
            'is_play',
            'create_time',
            'browse_num'
        )
            ->where(function ($query) use ($keywords) {
                $query->where('title', 'like', "%$keywords%");
            })->where(function ($query) use ($node, $is_play, $start_time, $end_time, $create_start_time, $create_end_time) {
                if ($node) {
                    $query->where('node', $node);
                }
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('con_start_time', [$start_time, $end_time]);
                }
                if ($create_start_time && $create_end_time) {
                    $query->whereBetween('create_time', [$create_start_time, $create_end_time]);
                }
            })
            ->where('is_del', 1)
            // ->where(function($query) use($manage_lib_ids){
            //     if ($manage_lib_ids) {
            //         $query->whereIn('lib_id', $manage_lib_ids);//后端独有
            //     }
            // })
            ->orderByDesc('con_start_time')
            ->paginate($limit)
            ->toArray();


        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
        }

        return $res;
    }


    /**
     * 列表
     * @param user_id int 用户id
     * @param limit int 分页大小
     * @param node int 0 全部 活动类型    1 独立活动  2 多馆联合   
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 比赛开始时间(开始)
     * @param end_time datetime 比赛结束时间(开始)
     * @param is_play 是否发布 0全部  1 发布  2未发布
     */
    public function myContestLists($node, $user_id, $keywords, $start_time, $end_time, $is_play = 1, $limit = 10)
    {
        //  $manage_lib_ids = request()->manage_lib_ids;

        $res = $this->from('contest_activity as c')
            ->select(
                'c.id',
                'c.node',
                'c.title',
                'c.app_img as img',
                'c.host_handle',
                'c.tel',
                'c.con_start_time',
                'c.con_end_time',
                'c.vote_start_time',
                'c.vote_end_time',
                'c.is_reader',
                'c.vote_way',
                'c.number'/* ,'originals','promise' */,
                'c.intro',
                'c.rule_content',
                'c.is_play',
                'c.create_time'
            )
            ->join('contest_activity_works as w', 'w.con_id', '=', 'c.id')
            ->where(function ($query) use ($keywords) {
                $query->where('c.title', 'like', "%$keywords%");
            })->where(function ($query) use ($node, $is_play, $start_time, $end_time) {
                if ($node) {
                    $query->where('c.node', $node);
                }
                if ($is_play) {
                    $query->where('c.is_play', $is_play);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('c.con_start_time', [$start_time, $end_time]);
                }
            })
            ->where('c.is_del', 1)
            ->where('w.user_id', $user_id)
            ->where('w.status', '<>', 5) //不等于5，已删除
            // ->where(function($query) use($manage_lib_ids){
            //     if ($manage_lib_ids) {
            //         $query->whereIn('lib_id', $manage_lib_ids);//后端独有
            //     }
            // })
            ->groupBy('c.id')
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = strip_tags($val['intro']);
        }

        return $res;
    }



    /**
     * 根据node 获取 对应值
     * @param node 上传文件类型，连接  1.图片(默认)  2.文字  3.音频  4.视频  多个逗号链接
     */
    public function getNodeName($node)
    {
        $node = explode(',', $node);
        if (empty($node)) {
            return "图片、文字、音频、视频";
        }
        $node_name = '';
        if (in_array(1, $node)) {
            $node_name .= '、' . '图片';
        }
        if (in_array(2, $node)) {
            $node_name .= '、' . '文字';
        }
        if (in_array(3, $node)) {
            $node_name .= '、' . '音频';
        }
        if (in_array(4, $node)) {
            $node_name .= '、' . '视频';
        }

        return trim($node_name, '、');
    }



    /**
     * 获取活动状态
     * $data 活动数组
     * 
     * $status 1.大赛未开始  2 投稿中  3 投票未开始  4 投票中  5 投票已结束  6 大赛已结束 
     */
    public function getContestStatus($data)
    {
        $time = date('Y-m-d H:i:s');
        if ($data['con_start_time'] > $time) {
            $status = 1;
        } else if ($data['con_start_time'] < $time && $data['con_end_time'] > $time) {
            $status = 2;
        } else if ($data['vote_start_time'] > $time && $data['con_end_time'] < $time) {
            $status = 3;
        } else if ($data['vote_start_time'] < $time && $data['vote_end_time'] > $time) {
            $status = 4;
        } else if ($data['vote_end_time'] < $time && $data['con_end_time'] > $time) {
            $status = 5;
        } else {
            $status = 6;
        }
        return $status;
    }
}
